package vip.specimen.system.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.specimen.system.datasource.entity.SystemEmailConfigEntity;
import vip.specimen.system.repository.SystemEmailConfigRepository;
import vip.specimen.system.datasource.validation.SystemEmailConfigValidation;

import java.util.Calendar;

/**
 * *@Author: 余浪人
 * *@Date：2021/02/20 17:07
 * *@Email:yulangren520@Gmail.com
 * *@QQ:1368419640
 **/
@Service
public class SystemEmailConfigService {
    @Autowired
    private SystemEmailConfigRepository emailRepository;

    /**
     * 初始化Email配置
     *
     * @return 配置对象
     */
    public SystemEmailConfigEntity initialize() {
        SystemEmailConfigEntity email = new SystemEmailConfigEntity("", 25, "", "");
        this.emailRepository.save(email);
        return email;
    }

    /**
     * 获取Email配置
     *
     * @return Email配置
     */
    public SystemEmailConfigEntity getConf() {
        return this.emailRepository.count() < 1 ? this.initialize() : this.emailRepository.findFirstByOrderByCreateTimeDesc();
    }

    /**
     * 更新Email配置信息
     *
     * @param emailConfigValidation Email验证对象
     * @return Email
     */
    @Transactional
    public SystemEmailConfigEntity update(SystemEmailConfigValidation emailConfigValidation) {
        SystemEmailConfigEntity emailGetConf = this.getConf();
        emailGetConf.setEmailAddress(emailConfigValidation.getEmailAddress());
        emailGetConf.setEmailPost(emailConfigValidation.getEmailPost());
        emailGetConf.setEmailAccount(emailConfigValidation.getEmailAccount());
        emailGetConf.setEmailPassword(emailConfigValidation.getEmailPassword());
        emailGetConf.setUpdateTime(Calendar.getInstance().getTime());
        this.emailRepository.save(emailGetConf);
        return emailGetConf;
    }

}
